package com.example.education.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.SocketException;
import java.util.Properties;

public class FtpUtils {
    //ftp服务器地址
    private String hostname;
    //ftp服务器端口号默认为21
    private Integer port;
    //ftp登录账号
    private String username;
    //ftp登录密码
    private String password;
    private static FTPClient ftpClient = null;
    private static FtpUtils ftpUtils=null;


    private FtpUtils() {
        try {
            Resource resource = new ClassPathResource("source.properties");
            Properties props = PropertiesLoaderUtils.loadProperties(resource);
            hostname = props.getProperty("ftp_address");
            port = Integer.parseInt(props.getProperty("ftp_port"));
            username = props.getProperty("ftp_userName");
            password = props.getProperty("ftp_password");
            connectionFTPServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //单例模式拿对象
    public static FtpUtils getInstance() {
        if(ftpClient==null){
            ftpUtils = new FtpUtils();
        }
        return ftpUtils;
    }

    //获取链接
    private void connectionFTPServer() {
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(hostname, port);
            ftpClient.login(username, password);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("==============未连接到FTP，用户名或密码错误=================");
                ftpClient.disconnect();
            } else {
                System.out.println("==============连接到FTP成功=================");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("==============FTP的IP地址错误==============");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("==============FTP的端口错误==============");
        }
    }

    //删除文件
    public boolean deleteFile(String ftpDirAndFileName) {
        if (!ftpClient.isConnected()) {
            connectionFTPServer();
        }
        try {
            return ftpClient.deleteFile(ftpDirAndFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            close();
        }
    }

    //删除目录
    public boolean deleteDirectory(String ftpDirectory) {
        if (!ftpClient.isConnected()) {
            connectionFTPServer();
        }
        try {
            return ftpClient.removeDirectory(ftpDirectory);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            close();
        }
    }

    //获取目录下的文件列表
    public FTPFile[] getFileList(String filePath) {
        if (!ftpClient.isConnected()) {
            connectionFTPServer();
        }
        try {
            return ftpClient.listFiles(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            close();
        }
    }

    //创建文件夹
    public boolean mkDir(String ftpPath) {
        if (!ftpClient.isConnected()) {
            connectionFTPServer();
        }
        try {
            char[] chars = ftpPath.toCharArray();
            StringBuffer sbStr = new StringBuffer(256);
            for (int i = 0; i < chars.length; i++) {
                if ('\\' == chars[i]) {
                    sbStr.append('/');
                } else {
                    sbStr.append(chars[i]);
                }
            }
            ftpPath = sbStr.toString();
            ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
            ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 上传单个文件	 *
     *
     * @param newFileName 新文件名
     * @param folder      自定义保存的文件夹
     * @return 上传结果
     */
    public boolean uploadSingleAttachment(MultipartFile multipartFile, String newFileName, String folder) {
        if (!ftpClient.isConnected()) {
            connectionFTPServer();
        }
        boolean result = false;
        if (ftpClient != null) {
            try {
                if (StringUtils.isNotEmpty(folder)) {
                    mkDir(folder);
                }
                ftpClient.setBufferSize(100000);
                ftpClient.setControlEncoding("utf-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                result = ftpClient.storeFile(new String(newFileName.getBytes(), "iso-8859-1"), multipartFile.getInputStream());
            } catch (Exception e) {
                close();
                e.printStackTrace();
                return false;
            } finally {
                if (ftpClient.isConnected()) {
                    close();
                }
            }
        }
        return result;
    }

    //关闭ftp连接
    public void close() {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FtpUtils ftpUtils = getInstance();
        ftpUtils.mkDir("dubbo");
        ftpUtils.deleteDirectory("dubbo");
    }

}